package diploma.kisel.modelas.gui;

import static diploma.kisel.modelas.service.StaticHelper.nullToEmptyString;
import static diploma.kisel.modelas.validation.Validation.isNumber;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpringLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import diploma.kisel.modelas.domain.Computer;
import diploma.kisel.modelas.domain.ComputerType;
import diploma.kisel.modelas.domain.Concept;
import diploma.kisel.modelas.domain.Device;
import diploma.kisel.modelas.domain.DeviceType;
import diploma.kisel.modelas.gui.common.Const;
import diploma.kisel.modelas.gui.common.CurrentVar;
import diploma.kisel.modelas.service.ComputerServiceImpl;
import diploma.kisel.modelas.service.DeviceServiceImpl;
import diploma.kisel.modelas.service.DeviceTypeServiceImpl;
import diploma.kisel.modelas.service.UserServiceImpl;
import diploma.kisel.modelas.service.api.ComputerService;
import diploma.kisel.modelas.service.api.DeviceService;
import diploma.kisel.modelas.service.api.DeviceTypeService;
import diploma.kisel.modelas.service.api.UserService;
import javax.swing.JComboBox;
import javax.swing.border.CompoundBorder;
import javax.swing.border.BevelBorder;

/**
 * This window is used to display all devices. 
 * 
 * @author Nikolay Kisel
 *
 */
public class DeviceCatalogWindow extends JFrame {

	private static DeviceCatalogWindow frame;

	private int row;
	private JPanel contentPane;
	private static JTable table;
	private static DefaultTableModel model;
	private JScrollPane scrollPane;
	private static Vector<Vector<Object>> tableData;
	// private ComputerService computerService = new ComputerServiceImpl();
	private DeviceService deviceService = new DeviceServiceImpl();

	
	private JLabel label;
	private JTextField textFieldMinPrice;
	private JTextField textFieldMaxPrice;
	private JButton buttonAdd;
	private JButton buttonClose;

	// Defines frame the application has come from
	private boolean isFromServerWindow = false;
	private boolean isFromWorkplaceWindow = false;

	private ServerWindow currServerWindow;
	private WorkplaceWindow currWorkplaceWindow;

	private DeviceTypeService deviceTypeService = new DeviceTypeServiceImpl();
	private UserService userService = new UserServiceImpl();
	private JPanel panelFiltr;
	private JLabel label_2;
	
	private JComboBox comboBox;
	private SpringLayout sl_panelFiltr;

	
	/**
	 * Create the frame.
	 */
	public DeviceCatalogWindow() {
		setTitle("Каталог устройств");
		// setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 508, 540);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		SpringLayout sl_contentPane = new SpringLayout();
		contentPane.setLayout(sl_contentPane);

		scrollPane = new JScrollPane();
		sl_contentPane.putConstraint(SpringLayout.NORTH, scrollPane, 95, SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, scrollPane, 0, SpringLayout.WEST, contentPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, scrollPane, 0, SpringLayout.EAST, contentPane);
		contentPane.add(scrollPane);

		table = new JTable(modelSetting(model, deviceService.findAll()));
		TableColumn col = table.getColumnModel().getColumn(0);
		col.setMinWidth(0);
		col.setMaxWidth(0);

		table.setAutoCreateRowSorter(true);
		scrollPane.setViewportView(table);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					Device device = new Device();
					device.setId((Integer) table.getValueAt(row, 0));
					device.setNumber((String) table.getValueAt(row, 1));
					device.setBrand((String) table.getValueAt(row, 2));
					device.setCost((Integer) table.getValueAt(row, 3));
					device.setFeatures((String) table.getValueAt(row, 4));
					String deviceTypeId = (String) table.getValueAt(row, 5);
					device.setDeviceType(deviceTypeService
							.findById(deviceTypeId));
					if (!isFromServerWindow && !isFromWorkplaceWindow) {
						DeviceWindow deviceWindow = new DeviceWindow();
						DeviceWindow.setFrame(deviceWindow);
						deviceWindow.setDevice(device);
						deviceWindow.init();
						deviceWindow.setVisible(true);
					} else {
						if (isFromServerWindow)
							currServerWindow.setNewModelForDevice(device);
						else
							currWorkplaceWindow.setNewModelForDevice(device);
						JOptionPane.showMessageDialog(frame, "База данных добавлена");
					}
				}
			}
		});

		ListSelectionModel listSelMod = table.getSelectionModel();
		listSelMod.addListSelectionListener(new ListSelectionListener() {

			@Override
			public void valueChanged(ListSelectionEvent e) {
				row = table.getSelectedRow();
				// System.out.println(row);
			}
		});

		buttonAdd = new JButton("Добавить");
		sl_contentPane.putConstraint(SpringLayout.SOUTH, scrollPane, -14, SpringLayout.NORTH, buttonAdd);
		buttonAdd.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Device device = new Device();
				DeviceWindow deviceWindow = new DeviceWindow();
				DeviceWindow.setFrame(deviceWindow);
				deviceWindow.setDevice(device);
				deviceWindow.setVisible(true);
				deviceWindow.getBtnDelete().setVisible(false);
			}
		});
		contentPane.add(buttonAdd);

		buttonClose = new JButton("Закрыть");
		sl_contentPane.putConstraint(SpringLayout.EAST, buttonClose, 0, SpringLayout.EAST, contentPane);
		buttonClose.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frame.setVisible(false);
			}
		});
		sl_contentPane.putConstraint(SpringLayout.SOUTH, buttonClose, 0,
				SpringLayout.SOUTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.NORTH, buttonAdd, 0,
				SpringLayout.NORTH, buttonClose);
		sl_contentPane.putConstraint(SpringLayout.EAST, buttonAdd, -8,
				SpringLayout.WEST, buttonClose);
		contentPane.add(buttonClose);
		
		panelFiltr = new JPanel();
		panelFiltr.setBorder(new CompoundBorder(new BevelBorder(BevelBorder.RAISED, null, null, null, null), new BevelBorder(BevelBorder.LOWERED, null, null, null, null)));
		sl_contentPane.putConstraint(SpringLayout.NORTH, panelFiltr, 0, SpringLayout.NORTH, contentPane);
		sl_contentPane.putConstraint(SpringLayout.WEST, panelFiltr, 0, SpringLayout.WEST, scrollPane);
		sl_contentPane.putConstraint(SpringLayout.SOUTH, panelFiltr, -6, SpringLayout.NORTH, scrollPane);
		sl_contentPane.putConstraint(SpringLayout.EAST, panelFiltr, 0, SpringLayout.EAST, scrollPane);
		contentPane.add(panelFiltr);
		sl_panelFiltr = new SpringLayout();
		panelFiltr.setLayout(sl_panelFiltr);
		
				label = new JLabel("Мин. цена");
				sl_panelFiltr.putConstraint(SpringLayout.NORTH, label, 10, SpringLayout.NORTH, panelFiltr);
				sl_panelFiltr.putConstraint(SpringLayout.WEST, label, 10, SpringLayout.WEST, panelFiltr);
				sl_contentPane.putConstraint(SpringLayout.WEST, label, 0, SpringLayout.WEST, panelFiltr);
				sl_contentPane.putConstraint(SpringLayout.SOUTH, label, 0, SpringLayout.SOUTH, panelFiltr);
				panelFiltr.add(label);
				
						textFieldMinPrice = new JTextField();
						sl_panelFiltr.putConstraint(SpringLayout.NORTH, textFieldMinPrice, -3, SpringLayout.NORTH, label);
						sl_panelFiltr.putConstraint(SpringLayout.WEST, textFieldMinPrice, 35, SpringLayout.EAST, label);
						sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldMinPrice, 57, SpringLayout.NORTH, panelFiltr);
						sl_contentPane.putConstraint(SpringLayout.WEST, textFieldMinPrice, 0, SpringLayout.WEST, panelFiltr);
						sl_contentPane.putConstraint(SpringLayout.SOUTH, textFieldMinPrice, 77, SpringLayout.NORTH, panelFiltr);
						sl_contentPane.putConstraint(SpringLayout.EAST, textFieldMinPrice, -396, SpringLayout.EAST, panelFiltr);
						panelFiltr.add(textFieldMinPrice);
						textFieldMinPrice.setColumns(10);
						
								JLabel label_1 = new JLabel("Макс. цена");
								sl_panelFiltr.putConstraint(SpringLayout.NORTH, label_1, 0, SpringLayout.NORTH, label);
								sl_panelFiltr.putConstraint(SpringLayout.WEST, label_1, 22, SpringLayout.EAST, textFieldMinPrice);
								sl_contentPane.putConstraint(SpringLayout.NORTH, label_1, 0, SpringLayout.NORTH, label);
								sl_contentPane.putConstraint(SpringLayout.WEST, label_1, 23, SpringLayout.EAST, textFieldMinPrice);
								sl_contentPane.putConstraint(SpringLayout.EAST, label_1, 79, SpringLayout.EAST, textFieldMinPrice);
								panelFiltr.add(label_1);
								
										textFieldMaxPrice = new JTextField();
										sl_panelFiltr.putConstraint(SpringLayout.NORTH, textFieldMaxPrice, -3, SpringLayout.NORTH, label);
										sl_panelFiltr.putConstraint(SpringLayout.WEST, textFieldMaxPrice, 23, SpringLayout.EAST, label_1);
										sl_contentPane.putConstraint(SpringLayout.NORTH, textFieldMaxPrice, -3, SpringLayout.NORTH, label);
										sl_contentPane.putConstraint(SpringLayout.WEST, textFieldMaxPrice, 25, SpringLayout.EAST, label_1);
										panelFiltr.add(textFieldMaxPrice);
										textFieldMaxPrice.setColumns(10);
										
												JButton button = new JButton("Фильтровать");
												sl_panelFiltr.putConstraint(SpringLayout.WEST, button, 0, SpringLayout.WEST, textFieldMaxPrice);
												sl_panelFiltr.putConstraint(SpringLayout.SOUTH, button, -10, SpringLayout.SOUTH, panelFiltr);
												sl_contentPane.putConstraint(SpringLayout.WEST, button, 0, SpringLayout.WEST, textFieldMaxPrice);
												sl_contentPane.putConstraint(SpringLayout.SOUTH, button, 0, SpringLayout.SOUTH, panelFiltr);
												sl_contentPane.putConstraint(SpringLayout.EAST, button, 384, SpringLayout.WEST, panelFiltr);
												panelFiltr.add(button);
												
												label_2 = new JLabel("Тип:");
												sl_panelFiltr.putConstraint(SpringLayout.NORTH, label_2, 18, SpringLayout.SOUTH, label);
												sl_panelFiltr.putConstraint(SpringLayout.WEST, label_2, 0, SpringLayout.WEST, label);
												panelFiltr.add(label_2);
												
												final JComboBox comboBox = createComboBox();
												panelFiltr.add(comboBox);
												button.addActionListener(new ActionListener() {
													public void actionPerformed(ActionEvent arg0) {
														if (isNumber(textFieldMinPrice.getText())) {
															int minPrice = Integer.valueOf(textFieldMinPrice.getText());
															if (isNumber(textFieldMaxPrice.getText())) {
																int maxPrice = Integer.valueOf(textFieldMaxPrice
																		.getText());
																DeviceType type = (DeviceType) comboBox.getSelectedItem();
																// System.out.println(minPrice + " " + maxPrice);
																table.setModel(modelSetting(model,
																		deviceService.findByPriceAndType(minPrice, maxPrice, type)));
																TableColumn col = table.getColumnModel().getColumn(0);
																col.setMinWidth(0);
																col.setMaxWidth(0);

																// scrollPane.setViewportView(table);
															} else
																JOptionPane.showMessageDialog(frame,
																		"Введено неверное число.");
														} else
															JOptionPane.showMessageDialog(frame,
																	"Введено неверное число.");

													}
												});
		
		if (userService.checkRole(CurrentVar.getCurrentUser(), Const.studentRole))
			buttonAdd.setVisible(false);
	}

	public static DefaultTableModel modelSetting(DefaultTableModel model,
			List<Device> devices) {

		tableData = new Vector<Vector<Object>>();
		// List<Computer> computers=computerService.findAll();
		for (Device device : devices) {
			Vector<Object> currRow = new Vector<Object>();
			currRow.add(device.getId());
			currRow.add(nullToEmptyString(device.getNumber()));
			currRow.add(nullToEmptyString(device.getBrand()));
			currRow.add(device.getCost());
			currRow.add(nullToEmptyString(device.getFeatures()));
			currRow.add(device.getDeviceType().getId());
			tableData.add(currRow);
		}

		Vector<String> columnName = new Vector<String>();
		columnName.add("Ид");
		columnName.add("Номер");
		columnName.add("Марка");
		columnName.add("Стоимость");
		columnName.add("Характеристики");
		columnName.add("Тип");

		model = new DefaultTableModel(tableData, columnName) {

			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int col) {
				return false;
			}

		};

		return model;
	}

	public static void setNewModel(List<Device> devices) {
		table.setModel(modelSetting(model, devices));
		TableColumn col = table.getColumnModel().getColumn(0);
		col.setMinWidth(0);
		col.setMaxWidth(0);
	}

	public static DeviceCatalogWindow getFrame() {
		return frame;
	}

	public static void setFrame(DeviceCatalogWindow frame) {
		DeviceCatalogWindow.frame = frame;
	}

	public boolean isFromServerWindow() {
		return isFromServerWindow;
	}

	public void setFromServerWindow(boolean isFromServerWindow) {
		this.isFromServerWindow = isFromServerWindow;
	}

	public ServerWindow getCurrServerWindow() {
		return currServerWindow;
	}

	public void setCurrServerWindow(ServerWindow currServerWindow) {
		this.currServerWindow = currServerWindow;
	}

	public WorkplaceWindow getCurrWorkplaceWindow() {
		return currWorkplaceWindow;
	}

	public void setCurrWorkplaceWindow(WorkplaceWindow currWorkplaceWindow) {
		this.currWorkplaceWindow = currWorkplaceWindow;
	}

	public boolean isFromWorkplaceWindow() {
		return isFromWorkplaceWindow;
	}

	public void setFromWorkplaceWindow(boolean isFromWorkplaceWindow) {
		this.isFromWorkplaceWindow = isFromWorkplaceWindow;
	}
	
	public JComboBox createComboBox() {
		List<DeviceType> types = deviceTypeService.findAll(); 
		Vector<Object> items = new Vector<>();
		for (DeviceType type : types) {
			items.add(type);
		}
		comboBox = new JComboBox(items);
		sl_panelFiltr.putConstraint(SpringLayout.NORTH, comboBox, -3, SpringLayout.NORTH, label_2);
		sl_panelFiltr.putConstraint(SpringLayout.WEST, comboBox, 0, SpringLayout.WEST, textFieldMinPrice);

		return comboBox;
	}
}
